import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import store from '@/store'

const getDefaultState = () => {
  return {
    token: '',
    // refreshToken: '', // 这个刷新 token 没有功能不做
    name: '',
    avatar: '',
    // 这个字段存储所有后端返回的数据
    introduction: '',
    // 这个参数先写死，这一期还没有那个位置会去更改此字段,权限判断
    userRolesOptions: [
      {
        id: 1,
        userName: '爵奇管理员'
      }, {
        id: 2,
        userName: '爵奇成员'
      }, {
        id: 3,
        userName: '品牌商管理员'
      }, {
        id: 4,
        userName: '品牌商成员'
      }
    ],
    // 当前的角色
    userCurRole: '',
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // SET_REFRESH_TOKEN: (state, refreshToken) => {
  //   state.refreshToken = refreshToken
  // },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USER_CUR_ROLE: (state, userCurRole) => {
    state.userCurRole = userCurRole
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response

        if (response.code === 200 && data) {
          const introduction = data.user
          commit('SET_TOKEN', data.accessToken)
          // commit('SET_REFRESH_TOKEN', data.refreshToken)
          commit('SET_INTRODUCTION', introduction)
          commit('SET_USER_CUR_ROLE', introduction.role)

          setToken(data.accessToken)
        }

        resolve(response)
      }).catch(error => {
        console.log('登陆失败')
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        // 暂时没有地方调用这个接口

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        resolve()
      }).catch(error => {
        reject(error)
      }).finally(() => {
        commit('RESET_STATE')
        store.commit('permission/RESET_STATE')

        removeToken()
        resetRouter()
        router.push('/login')
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('RESET_STATE')

      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {

    // 暂时没有地方调用这个方法

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
